package org.kl.wxWeb.web;

import javax.servlet.http.HttpSession;

import me.chanjar.weixin.common.exception.WxErrorException;
import me.chanjar.weixin.mp.api.WxMpService;
import me.chanjar.weixin.mp.bean.result.WxMpOAuth2AccessToken;

import org.apache.commons.lang3.StringUtils;
import org.kl.bf.service.basic.UserService;
import org.kl.bf.utils.BasicConstants;
import org.kl.bf.web.base.BasicController;
import org.kl.wx.entity.App;
import org.kl.wx.entity.WxUser;
import org.kl.wx.service.AppService;
import org.kl.wx.service.WxUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springside.modules.web.MediaTypes;

@Controller
@RequestMapping(value = "/wxWeb/wxWebBasic")
public class WxWebBasicController extends BasicController {

	@Autowired
	private WxUserService wxUserService;
	@Autowired
	private UserService userService;
	@Autowired
	private AppService appService;

	@RequestMapping(method = RequestMethod.GET)
	public String list() {
		return "/wxWeb/wxBasicPage";
	}

	@RequestMapping(value = "checkUser", produces = MediaTypes.JAVASCRIPT_UTF_8)
	@ResponseBody
	public String checkUser(@RequestParam(value = "code", defaultValue = "") String code,
			@RequestParam(value = "appid", defaultValue = "") String appId, @RequestParam(value = "state", defaultValue = "") String state,
			HttpSession session) {
		WxMpService wxMpService = super.getWxMpServiceByAppId(session, appId);
		App app = appService.getAppByOriginAppId(appId);
		try {
			WxMpOAuth2AccessToken wxMp = wxMpService.oauth2getAccessToken(code);
			WxUser wxUser = wxUserService.getByAppIdAndOpenid(app.getId(), wxMp.getOpenId());
			String url = BasicConstants.SYSTOM_URL;
			if (StringUtils.isBlank(wxUser.getUnionid())) {
				url += "/wxWeb/bindingWxUser?openid=" + wxMp.getOpenId() + "&appid=" + app.getId() + "&state=" + state;
				return ajaxMsg("您尚未绑定系统账号,将跳转到绑定界面.", false, url);
			} else {
				if (userService.getUser(wxUser.getUnionid()) == null
						|| StringUtils.isBlank(userService.getUser(wxUser.getUnionid()).getId())) {
					url += "/wxWeb/bindingWxUser?openid=" + wxMp.getOpenId() + "&appid=" + app.getId() + "&state=" + state;
					return ajaxMsg("您绑定的系统账号已失效,将跳转到绑定界面.", false, url);
				} else {
					// 通过state传递对应的controller路径
					url += "/wxWeb/" + state + "?openid=" + wxMp.getOpenId() + "&appid=" + app.getId();
					System.out.println(url);
					return ajaxMsg("", true, url);
				}
			}
		} catch (WxErrorException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			return ajaxMsg(e.toString(), false, null);
		}
	}
}
